import { HASH_CHUNK_SIZE, computeHash, blobSlice } from '../index';

/**
 * 创建分片线程
 *
 * @param {Object} e.data
 * @param {Number} e.data.threadIndex 线程索引
 * @param {Number} e.data.threadCount 线程数量
 * @param {File} e.data.file 文件
 * @returns {Array} 分片结果
 */
onmessage = (e) => {
  let { file } = e.data;
  const chunkCount = Math.ceil(file.size / HASH_CHUNK_SIZE); // 分片数量

  const result = [];
  for (let index = 0; index < chunkCount; index++) {
    const startIndex = index * HASH_CHUNK_SIZE;
    const endIndex = Math.min(startIndex + HASH_CHUNK_SIZE, file.size);
    const chunkFile = blobSlice.call(file, startIndex, endIndex, file.type);

    result.push(computeHash(chunkFile));
  }

  Promise.all(result).then((res) => postMessage(res));
};
